import { combineURLs } from '../utils/index.js';

import { isFormData } from 'src/utils/validate/data.js';
import { forEach } from 'src/utils/index.js';

const transformData = (data, headers, fns) => {
	/*eslint no-param-reassign:0*/
	forEach(fns, function transform(fn) {
		data = fn(data, headers);
	});
	return data;
};

const uniRequest = config => {
	// 处理URL
	const fullUrl = combineURLs(config.baseURL, config.url);
	// 处理请求头
	config.headers = config.headers || {};

	// 如果设置了 config.trasformRequest , 通过transformRequest去处理
	config.data = transformData(config.data, config.headers, config.transformRequest);

	return new Promise((resolve, reject) => {
		// 处理 FormData类型的值
		if (isFormData(config.data)) {
			delete config.headers['Content-Type'];
		}
		uni.request({
			url: fullUrl,
			data: config.data || {},
			header: config.headers,
			method: config.method,
			timeout: config.timeout,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			success: responese => {
				// 请求成功的处理
				console.log(responese.data);
				responese.data = transformData(responese.data, responese.headers, config.transformResponse);
				resolve(responese);
			},
			fail: reason => {
				// 请求成功的处理
				console.log(reason.data);
				reason.data = transformData(reason.data, reason.headers, config.transformResponse);
				reject(reason);
			},
		});
	});
};
export default uniRequest;
